import { createRouter, createWebHistory } from "vue-router";
import NProgress from "nprogress"; // progress bar
import userRoutes from "./user";
import doctorRoutes from "./doctor";
import basicRoutes from "./basic";
import payment from "./payment";
import eventEmitter from "@/api/eventEmitter";
import "nprogress/nprogress.css"; // progress bar style
import { getStorage } from "@/utils/local";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const routes = [
	{
		path: "/basic",
		redirect: "/basic/enter",
		children: [...basicRoutes],
	},
	{
		path: "/login",
		name: "login",
		component: () => import("@/views/login/LoginIndex.vue"),
		meta: {
			keepAlive: false,
			title: "登录",
			requiresAuth: "user",
		},
	},
	{
		path: "/user",
		component: () => import("../views/user/UserRouterView.vue"),
		children: [...userRoutes],
	},
	{
		path: "/doctor",
		children: [...doctorRoutes],
	},
	{
		path: "/payment",
		children: [...payment],
	},
	{
		path: "/:pathMatch(.*)*",
		redirect: "/user/enter",
		meta: {
			title: "404",
		},
	},
];

console.log(routes);
const router = createRouter({
	history: createWebHistory(import.meta.env.VITE_APP_BASE_URL || "/"),
	routes,
});

router.beforeEach((to, from, next) => {
	console.log(to);
	NProgress.start();
	document.title = to.meta.title || "";
	if (to.name !== "login" && Object.keys(getStorage("info") || {}).length === 0) {
		next({
			name: "login",
			query: {
				redirect: to.name,
				...to.query,
			},
			replace: true,
		});
	}
	next();
});

/**
 * @description 路由后置，跳转结束
 */
router.afterEach(() => {
	// finish progress bar
	NProgress.done();
});

eventEmitter.on("API:UN_AUTH", () => {
	router.push("/login");
});

export default router;
